package com.ybkj.daijia.server.event.listener.gasstation;

import com.ybkj.daijia.OrderNumberConfig;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.server.event.model.gasstation.GasRebateEvent;
import com.ybkj.daijia.server.gasstation.Order;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerAccount;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.FinancialRecord;
import com.ybkj.daijia.server.model.GasRebate;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverPaymentsRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FinancialRecordService;
import com.ybkj.daijia.server.service.GasRebateService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberPaymentsRecordService;
import com.ybkj.daijia.server.service.MemberService;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class GasRebateEventListener implements ApplicationListener<GasRebateEvent> {

    private static final Logger logger = LoggerFactory.getLogger(GasRebateEventListener.class);

    @Autowired
    private MemberService memberService;

    @Autowired
    private DriverService driverService;

    @Autowired
    private GasRebateService gasRebateService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private FinancialRecordService financialRecordService;

    @Autowired
    private MemberPaymentsRecordService memberPaymentsRecordService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private DriverPaymentsRecordService driverPaymentsRecordService;


    @Override
    @Async
    public void onApplicationEvent(GasRebateEvent event) {

        logger.debug("GasRebateEvent event:{}", "");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Passenger passenger = (Passenger) event.getSource();
        Order order = event.getOrder();
        BigDecimal realCash = event.getRealCash();
        Integer introduceType = passenger.getIntroduceType();//0客户推荐 1服务人员推荐

        if (null != introduceType) {
            if (introduceType.equals(0)) {//客户推荐
                GasRebate gasRebate = gasRebateService.findByCompany(passenger.getCompanyId());

                if (null != gasRebate) {

                    if (StringUtils.isNotBlank(passenger.getIntroducer())) {

                        //第一级
                        Passenger firstPassenger = memberService
                            .findOnePassengerByPhone(passenger.getIntroducer());
                        if (null != firstPassenger && gasRebate.getLevel() >= 1) {
                            if (firstPassenger.getCompanyId() == passenger.getCompanyId()) {
                                if (gasRebate.getGasRebateType1()
                                    .equals(GasRebate.GasRebateType.guding)) {
                                    if (null != gasRebate.getMoney1()
                                        && gasRebate.getMoney1().compareTo(BigDecimal.ZERO) == 1) {
                                        saveFinancialRecord(passenger, firstPassenger, order,
                                            gasRebate.getMoney1(), 1);
                                    }
                                } else if (gasRebate.getGasRebateType1()
                                    .equals(GasRebate.GasRebateType.percent)) {
                                    if (null != gasRebate.getCommission1()
                                        && gasRebate.getCommission1().compareTo(BigDecimal.ZERO)
                                        == 1) {
                                        BigDecimal money = realCash
                                            .multiply(gasRebate.getCommission1())
                                            .divide(new BigDecimal(100));
                                        saveFinancialRecord(passenger, firstPassenger, order, money,
                                            1);
                                    }
                                }
                            }

                            if (StringUtils.isNotBlank(firstPassenger.getIntroducer())) {
                                //第二级
                                Passenger secondPassenger = memberService
                                    .findOnePassengerByPhone(firstPassenger.getIntroducer());
                                if (null != secondPassenger && gasRebate.getLevel() >= 2) {
                                    if (secondPassenger.getCompanyId() == passenger
                                        .getCompanyId()) {
                                        if (gasRebate.getGasRebateType2()
                                            .equals(GasRebate.GasRebateType.guding)) {
                                            if (null != gasRebate.getMoney2()
                                                && gasRebate.getMoney2().compareTo(BigDecimal.ZERO)
                                                == 1) {
                                                saveFinancialRecord(passenger, secondPassenger,
                                                    order, gasRebate.getMoney2(), 2);
                                            }
                                        } else if (gasRebate.getGasRebateType2()
                                            .equals(GasRebate.GasRebateType.percent)) {
                                            if (null != gasRebate.getCommission2() &&
                                                gasRebate.getCommission2()
                                                    .compareTo(BigDecimal.ZERO) == 1) {
                                                BigDecimal money = realCash
                                                    .multiply(gasRebate.getCommission2())
                                                    .divide(new BigDecimal(100));
                                                saveFinancialRecord(passenger, secondPassenger,
                                                    order, money, 2);
                                            }
                                        }
                                    }

                                    if (StringUtils.isNotBlank(secondPassenger.getIntroducer())) {
                                        //第三级
                                        Passenger thirdPassenger = memberService
                                            .findOnePassengerByPhone(
                                                secondPassenger.getIntroducer());
                                        if (null != thirdPassenger && gasRebate.getLevel() >= 3) {
                                            if (thirdPassenger.getCompanyId() == passenger
                                                .getCompanyId()) {
                                                if (gasRebate.getGasRebateType3()
                                                    .equals(GasRebate.GasRebateType.guding)) {
                                                    if (null != gasRebate.getMoney3() &&
                                                        gasRebate.getMoney3()
                                                            .compareTo(BigDecimal.ZERO) == 1) {
                                                        saveFinancialRecord(passenger,
                                                            thirdPassenger, order,
                                                            gasRebate.getMoney3(), 3);
                                                    }
                                                } else if (gasRebate.getGasRebateType3()
                                                    .equals(GasRebate.GasRebateType.percent)) {
                                                    if (null != gasRebate.getCommission3() &&
                                                        gasRebate.getCommission3()
                                                            .compareTo(BigDecimal.ZERO) == 1) {
                                                        BigDecimal money = realCash
                                                            .multiply(gasRebate.getCommission3())
                                                            .divide(new BigDecimal(100));
                                                        saveFinancialRecord(passenger,
                                                            thirdPassenger, order, money, 3);
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (introduceType.equals(1)) {//服务人员推荐
                GasRebate gasRebate = gasRebateService.findByCompany(passenger.getCompanyId());

                if (null != gasRebate) {

                    if (StringUtils.isNotBlank(passenger.getIntroducer())) {
                        //第一级
                        Driver firstDriver = driverService
                            .findByUsername(passenger.getIntroducer());
                        if (null != firstDriver && gasRebate.getLevel() >= 1) {
                            if (firstDriver.getCompanyId() == passenger.getCompanyId()) {
                                if (gasRebate.getGasRebateType1()
                                    .equals(GasRebate.GasRebateType.guding)) {
                                    if (null != gasRebate.getMoney1()
                                        && gasRebate.getMoney1().compareTo(BigDecimal.ZERO) == 1) {
                                        firstDriver.setVirtual(
                                            firstDriver.getVirtual().add(gasRebate.getMoney1()));
                                        driverService.updateVirtual(firstDriver);

                                        saveDriverFinancialRecord(passenger, firstDriver, order,
                                            gasRebate.getMoney1(), 1);
                                    }
                                } else if (gasRebate.getGasRebateType1()
                                    .equals(GasRebate.GasRebateType.percent)) {
                                    if (null != gasRebate.getCommission1()
                                        && gasRebate.getCommission1().compareTo(BigDecimal.ZERO)
                                        == 1) {
                                        BigDecimal money = realCash
                                            .multiply(gasRebate.getCommission1())
                                            .divide(new BigDecimal(100));
                                        firstDriver.setVirtual(firstDriver.getVirtual().add(money));
                                        driverService.updateVirtual(firstDriver);

                                        saveDriverFinancialRecord(passenger, firstDriver, order,
                                            money, 1);
                                    }
                                }
                            }

                            if (StringUtils.isNotBlank(firstDriver.getIntroducer())) {
                                //第二级
                                Driver secondDriver = driverService
                                    .findByUsername(firstDriver.getIntroducer());
                                if (null != secondDriver && gasRebate.getLevel() >= 2) {
                                    if (secondDriver.getCompanyId() == passenger.getCompanyId()) {
                                        if (gasRebate.getGasRebateType2()
                                            .equals(GasRebate.GasRebateType.guding)) {
                                            if (null != gasRebate.getMoney2()
                                                && gasRebate.getMoney2().compareTo(BigDecimal.ZERO)
                                                == 1) {
                                                secondDriver.setVirtual(secondDriver.getVirtual()
                                                    .add(gasRebate.getMoney2()));
                                                driverService.updateVirtual(secondDriver);

                                                saveDriverFinancialRecord(passenger, secondDriver,
                                                    order, gasRebate.getMoney2(), 2);
                                            }
                                        } else if (gasRebate.getGasRebateType2()
                                            .equals(GasRebate.GasRebateType.percent)) {
                                            if (null != gasRebate.getCommission2() &&
                                                gasRebate.getCommission2()
                                                    .compareTo(BigDecimal.ZERO) == 1) {
                                                BigDecimal money = realCash
                                                    .multiply(gasRebate.getCommission2())
                                                    .divide(new BigDecimal(100));
                                                secondDriver.setVirtual(
                                                    secondDriver.getVirtual().add(money));
                                                driverService.updateVirtual(secondDriver);

                                                saveDriverFinancialRecord(passenger, secondDriver,
                                                    order, money, 2);
                                            }
                                        }
                                    }

                                    if (StringUtils.isNotBlank(secondDriver.getIntroducer())) {
                                        //第三级
                                        Driver thirdDriver = driverService
                                            .findByUsername(secondDriver.getIntroducer());
                                        if (null != thirdDriver && gasRebate.getLevel() >= 3) {
                                            if (thirdDriver.getCompanyId() == passenger
                                                .getCompanyId()) {
                                                if (gasRebate.getGasRebateType3()
                                                    .equals(GasRebate.GasRebateType.guding)) {
                                                    if (null != gasRebate.getMoney3() &&
                                                        gasRebate.getMoney3()
                                                            .compareTo(BigDecimal.ZERO) == 1) {
                                                        thirdDriver.setVirtual(
                                                            thirdDriver.getVirtual()
                                                                .add(gasRebate.getMoney3()));
                                                        driverService.updateVirtual(thirdDriver);

                                                        saveDriverFinancialRecord(passenger,
                                                            thirdDriver, order,
                                                            gasRebate.getMoney3(), 3);
                                                    }
                                                } else if (gasRebate.getGasRebateType3()
                                                    .equals(GasRebate.GasRebateType.percent)) {
                                                    if (null != gasRebate.getCommission3() &&
                                                        gasRebate.getCommission3()
                                                            .compareTo(BigDecimal.ZERO) == 1) {
                                                        BigDecimal money = realCash
                                                            .multiply(gasRebate.getCommission3())
                                                            .divide(new BigDecimal(100));
                                                        thirdDriver.setVirtual(
                                                            thirdDriver.getVirtual().add(money));
                                                        driverService.updateVirtual(thirdDriver);

                                                        saveDriverFinancialRecord(passenger,
                                                            thirdDriver, order, money, 3);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                }
                            }

                        }
                    }

                }

            }
        }

    }

    public void saveFinancialRecord(Passenger sourcePassenger, Passenger introducer, Order order,
        BigDecimal money, int setup) {

        FinancialRecord financialRecord = new FinancialRecord();
        Company company = companyService.findOne(introducer.getCompanyId());

        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        StringBuilder sb = new StringBuilder();
        sb.append(OrderNumberConfig.FINANCIAL_MEMBERREBATE);//推荐提成
        sb.append(OrderNumberConfig.FINANCIAL_WHO_SYS);//系统添加
        sb.append(format.format(new Date()));//年月日时间
        sb.append(OrderNumberConfig.padZero(financialRecordService.getRunningNumber() + 1));//流水号
        financialRecord.setCode(sb.toString());
        financialRecord.setCompanyId(company.getId());
        financialRecord.setCompanyName(company.getAbbreviation());
        financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
        financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_MEMBERREBATE);
        financialRecord.setMoney(money.multiply(new BigDecimal(-1)));
        financialRecord.setOrderId(order.getId());
        Company orderCompany = companyService.findOne(order.getCompanyId());
        financialRecord.setOrderCompanyId(orderCompany.getId());
        financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());

        String memo =
            "客户【" + sourcePassenger.getName() + "（" + sourcePassenger.getPhone() + "）】加油,【"
                + introducer.getName() + "】获得" + setup + "级推荐提成" + money + "元,单号：" + order
                .getOrderNum();
        financialRecord.setMemo(memo);
        financialRecord.setWho(introducer.getName());
        financialRecordService.save(financialRecord);

        String memo2 =
            "客户【" + sourcePassenger.getName() + "（" + sourcePassenger.getPhone() + "）】加油,获得" + setup
                + "级推荐提成" + money + "元,单号：" + order.getOrderNum();

        Long orderId = order.getId();
        String orderNumber = order.getOrderNum();
        Integer orderType = PassengerAccount.ORDER_TYPE_GASSTATION;

        memberService.money(introducer, sourcePassenger.getId(), money, memo2,
            PassengerAccount.OPERATING_SYS, PassengerAccount.PayType.RECHARGE_TYPE_REBATE, orderId,
            orderNumber, orderType, null, true, false);

    }

    public void saveDriverFinancialRecord(Passenger sourcePassenger, Driver driver, Order order,
        BigDecimal money, int setup) {

        FinancialRecord financialRecord = new FinancialRecord();
        Company company = companyService.findOne(driver.getCompanyId());

        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        StringBuilder sb = new StringBuilder();
        sb.append(OrderNumberConfig.FINANCIAL_MEMBERREBATE);//推荐提成
        sb.append(OrderNumberConfig.FINANCIAL_WHO_SYS);//系统添加
        sb.append(format.format(new Date()));//年月日时间
        sb.append(OrderNumberConfig.padZero(financialRecordService.getRunningNumber() + 1));//流水号
        financialRecord.setCode(sb.toString());
        financialRecord.setCompanyId(company.getId());
        financialRecord.setCompanyName(company.getAbbreviation());
        financialRecord.setStatus(FinancialRecord.FINANCIALRECORD_OK);
        financialRecord.setType(FinancialRecord.FINANCIALRECORD_TYPE_MEMBERREBATE);
        financialRecord.setMoney(money.multiply(new BigDecimal(-1)));
        financialRecord.setOrderId(order.getId());
        Company orderCompany = companyService.findOne(order.getCompanyId());
        financialRecord.setOrderCompanyId(orderCompany.getId());
        financialRecord.setOrderCompanyName(orderCompany.getAbbreviation());

        String memo =
            "客户【" + sourcePassenger.getName() + "（" + sourcePassenger.getPhone() + "）】加油,服务人员【"
                + driver.getRealname() + "】获得" + setup + "级推荐提成" + money + "元,单号：" + order
                .getOrderNum();
        financialRecord.setMemo(memo);
        financialRecord.setWho(driver.getRealname());
        financialRecordService.save(financialRecord);

        //服务人员财务
        DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
        driverPaymentsRecord.setMoney(money);
        driverPaymentsRecord.setAfterMoney(driver.getVirtual());
        driverPaymentsRecord.setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_REBATE);
        driverPaymentsRecord.setDriverId(driver.getId());
        driverPaymentsRecord.setDriverRealName(driver.getRealname());
        driverPaymentsRecord.setDriverUserName(driver.getUsername());
        driverPaymentsRecord.setDriverPhone(driver.getPhone());
        driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
        driverPaymentsRecord.setOrderId(order.getId());
        driverPaymentsRecord.setOrderNumber(order.getOrderNum());
        driverPaymentsRecord.setOrderType(DriverPaymentsRecord.ORDER_TYPE_GASSTATION);
        driverPaymentsRecord.setOrderCompanyId(order.getCompanyId());
        String memo2 =
            "客户【" + sourcePassenger.getName() + "（" + sourcePassenger.getPhone() + "）】加油,获得" + setup
                + "级推荐提成" + money + "元,单号：" + order.getOrderNum();
        driverPaymentsRecord.setMemo(memo2);
        driverPaymentsRecord.setOperating(DriverPaymentsRecord.OPERATING_SYS);
        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
        driverPaymentsRecord.setHappend(new Date());
        driverPaymentsRecordService.insertRecord(driverPaymentsRecord);

    }

}
